package com.bytz.modules.cms.reseller.util;

import com.bytz.modules.system.security.vo.LoginReseller;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author shanxuezhong
 */
public class ResellerSecurityUtils {
    /**
     * 获取用户
     **/
    public static LoginReseller getLoginUser() {
        try {
            return (LoginReseller) getAuthentication().getPrincipal();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 设置LoginUser
     */
    public static void setLoginUser(LoginReseller user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }

    /**
     * 获取用户id
     */
    public static String getUserId() {
        LoginReseller loginUser = getLoginUser();
        if (loginUser != null) {
            return loginUser.getId();
        } else {
            return null;
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否匹配
     * @param oldpassword 密码
     * @param password 数据库密码
     * @return 是否能匹配
     */
    public static boolean matchesPassword(String oldpassword, String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(oldpassword, password);
    }
}
